package com.su02.multi.chainrule;

import com.su02.multi.util.BitSetUtil;

import java.util.Map;

public class Multiply extends Function {
    private final Function first;
    private final Function second;

    public Multiply(Function first, Function second) {
        this.first = first;
        this.second = second;
        this.setBs(BitSetUtil.or(this.first.getBs(), this.second.getBs()));
    }

    @Override
    public Function doBackward(int id) {
        Function ans;
        if (isNotRelated(id)) {
            ans = new Constant(0);
        } else {
            Function firstBackward = first.backward(id);
            Function secondBackward = second.backward(id);
            ans = firstBackward.mul(second).add(secondBackward.mul(first));
        }
        return ans;
    }

    @Override
    public double forward(Map<Integer, Double> vector) {
        assertVariablesMatch(vector);
        return first.forward(vector) * second.forward(vector);
    }
}
